<template>
  <view class="review-container">
    <!-- 产品信息区域 -->
    <view class="product-section">
      <view class="product-info">
        <image :src="productInfo.productImg" class="product-img" mode="aspectFill" />
        <view class="product-details">
          <view class="product-title">{{ productInfo.productName }}</view>
        </view>
      </view>
      
      <!-- 评分区域 -->
      <view class="rating-section">
        <view class="rating-label">综合评分</view>
        <view class="stars-container">
          <view 
            v-for="(star, index) in 5" 
            :key="index"
            :class="['star', { active: index < rating }]"
            @click="setRating(index + 1)"
          >
            <text class="star-icon">★</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 评论输入区域 -->
    <view class="review-section">
      <view class="review-prompt">亲,您对这个商品满意吗?您的评价会帮助我们选择更好的商品哦~</view>
      
      <view class="review-input-area">
        <textarea 
          v-model="reviewContent"
          class="review-textarea"
          placeholder="请输入您的评价内容..."
          maxlength="500"
        />
        
        <!-- 图片上传区域 -->
        <view class="image-upload-section">
          <view class="image-list">
            <view 
              v-for="(image, index) in uploadedImages" 
              :key="index"
              class="image-item"
            >
              <image :src="image" class="uploaded-img" mode="aspectFill" />
              <view class="delete-btn" @click="deleteImage(index)">×</view>
            </view>
            
            <view 
              v-if="uploadedImages.length < 6"
              class="add-image-btn"
              @click="chooseImage"
            >
              <view class="camera-icon">📷</view>
              <view class="add-text">添加图片</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 提交区域 -->
    <view class="submit-section">
      <view class="anonymous-option">
        <view 
          :class="['checkbox', { checked: isAnonymous }]"
          @click="toggleAnonymous"
        >
          <text v-if="isAnonymous" class="checkmark">✓</text>
        </view>
        <text class="anonymous-text">匿名评价</text>
      </view>
      
      <button 
        class="submit-btn"
        :disabled="!canSubmit"
        @click="submitReview"
      >
        提交评价
      </button>
    </view>
  </view>
</template>

<script>
import { submitReview, uploadReviewImage } from '@/api/review/review'
import { getUserProfile } from '@/api/system/user'
import store from '@/store'

export default {
  data() {
    return {
      orderId: '',
      productInfo: {
        productImg: '',
        productName: ''
      },
      rating: 0,
      reviewContent: '',
      uploadedImages: [],
      isAnonymous: false,
      userInfo: null
    }
  },
  computed: {
    canSubmit() {
      return this.rating > 0 && this.reviewContent.trim().length > 0
    }
  },
  methods: {
    setRating(rating) {
      this.rating = rating
    },
    
    async chooseImage() {
      uni.chooseImage({
        count: 6 - this.uploadedImages.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          // 使用若依的upload方法上传图片
          const uploadedUrls = []
          for (let i = 0; i < res.tempFilePaths.length; i++) {
            try {
              console.log('开始上传图片:', res.tempFilePaths[i])
              const uploadRes = await uploadReviewImage(res.tempFilePaths[i])
              console.log('上传响应:', uploadRes)
              
              if (uploadRes.code === 200 && uploadRes.data && uploadRes.data.url) {
                console.log('图片上传成功，URL:', uploadRes.data.url)
                uploadedUrls.push(uploadRes.data.url)
              } else {
                console.error('上传响应格式错误:', uploadRes)
                throw new Error(uploadRes.msg || '上传失败')
              }
            } catch (error) {
              console.error('图片上传失败:', error)
              uni.showToast({
                title: '图片上传失败',
                icon: 'none'
              })
            }
          }
          this.uploadedImages = [...this.uploadedImages, ...uploadedUrls]
        }
      })
    },
    
    deleteImage(index) {
      this.uploadedImages.splice(index, 1)
    },
    
    toggleAnonymous() {
      this.isAnonymous = !this.isAnonymous
    },
    
    async submitReview() {
      if (!this.canSubmit) {
        uni.showToast({
          title: '请完善评价信息',
          icon: 'none'
        })
        return
      }
      
      try {
        // 根据数据库表结构构建提交数据
        const reviewData = {
          orderId: this.orderId,
          productId: this.productInfo.productId,        // 商品id
          productName: this.productInfo.productName,    // 商品名称
          content: this.reviewContent,                   // 评论内容
          evaluation: this.rating,                       // 综合评分
          imgUrl: this.uploadedImages.length > 0 ? this.uploadedImages.join(',') : '',        // 评论图片（多个图片用逗号分隔）
          nickname: this.isAnonymous ? '匿名用户' : (this.userInfo ? this.userInfo.nickName : ''),   // 评论者昵称
          avatar: this.userInfo ? this.userInfo.avatar : '',                                    // 评论头像
          userId: this.userInfo ? this.userInfo.userId : '',                                   // 用户ID           // 删除标志（0代表存在）
          createTime: new Date().toISOString()          // 创建时间
        }
        
        console.log('提交评价数据:', reviewData)
        
        // 调用提交评价API
        const res = await submitReview(reviewData)
        
        if (res.code === 200) {
          uni.showToast({
            title: '评价提交成功',
            icon: 'success'
          })
          
          // 返回订单列表页面
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          throw new Error(res.message || '提交失败')
        }
        
      } catch (error) {
        console.error('提交评价失败:', error)
        uni.showToast({
          title: error.message || '提交失败，请重试',
          icon: 'none'
        })
      }
    },
    
    async loadUserInfo() {
      try {
        // 优先从store获取用户信息
        const storeUser = {
          userId: store.state.user.id,
          nickName: store.state.user.name,
          avatar: store.state.user.avatar
        }
        
        console.log('Store中的用户信息:', storeUser)
        
        // 如果store中没有完整信息，则调用API获取
        if (!storeUser.userId || !storeUser.nickName) {
          console.log('Store信息不完整，调用API获取用户信息')
          const res = await getUserProfile()
          if (res.code === 200 && res.data) {
            this.userInfo = {
              userId: res.data.userId || res.data.user_id,
              nickName: res.data.nickName || res.data.nick_name || res.data.userName,
              avatar: res.data.avatar
            }
            console.log('API获取的用户信息:', this.userInfo)
          } else {
            console.error('获取用户信息失败:', res)
            this.userInfo = storeUser
          }
        } else {
          this.userInfo = storeUser
        }
        
        // 验证关键字段
        if (!this.userInfo.userId) {
          console.error('用户ID字段缺失')
        }
        
        if (!this.userInfo.nickName) {
          console.warn('用户昵称字段缺失')
        }
        
        console.log('最终使用的用户信息:', this.userInfo)
        
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 使用store中的信息作为备选
        this.userInfo = {
          userId: store.state.user.id,
          nickName: store.state.user.name,
          avatar: store.state.user.avatar
        }
        console.log('使用store备选信息:', this.userInfo)
      }
    },
    
    loadProductInfo() {
      // 从页面参数或API获取产品信息
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      const options = currentPage.options
      
      console.log('评价页面参数:', options)
      
      if (options.orderId) {
        this.orderId = options.orderId
      }
      
      if (options.productImg) {
        this.productInfo.productImg = decodeURIComponent(options.productImg)
      }
      
      if (options.productName) {
        this.productInfo.productName = decodeURIComponent(options.productName)
      }
      
      if (options.productId) {
        this.productInfo.productId = options.productId
      }
      

      
      // 验证必要参数
      if (!this.orderId || !this.productInfo.productId || !this.productInfo.productName) {
        uni.showToast({
          title: '商品信息不完整，请重新选择',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        return
      }
      
      console.log('加载的产品信息:', this.productInfo)
    }
  },
  
  async onLoad(options) {
    this.loadProductInfo()
    await this.loadUserInfo()
  }
}
</script>

<style lang="scss" scoped>
.review-container {
  min-height: 100vh;
  background: #fafbfc;
  padding-bottom: 120px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.product-section {
  background: #fff;
  padding: 16px;
  margin-bottom: 12px;
}

.product-info {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
}

.product-img {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  margin-right: 12px;
  background: #f5f5f5;
  object-fit: cover;
}

.product-details {
  flex: 1;
}

.product-title {
  font-size: 16px;
  color: #333;
  line-height: 1.4;
  font-weight: 500;
}

.rating-section {
  display: flex;
  align-items: center;
}

.rating-label {
  font-size: 15px;
  color: #333;
  margin-right: 12px;
}

.stars-container {
  display: flex;
  align-items: center;
}

.star {
  margin-right: 8px;
  cursor: pointer;
  
  .star-icon {
    font-size: 24px;
    color: #ddd;
    transition: color 0.2s;
  }
  
  &.active .star-icon {
    color: #ff6b35;
  }
  
  &:hover .star-icon {
    color: #ff8c42;
  }
}

.review-section {
  background: #fff;
  padding: 16px;
  margin-bottom: 12px;
}

.review-prompt {
  font-size: 15px;
  color: #333;
  margin-bottom: 16px;
  line-height: 1.4;
}

.review-input-area {
  min-height: 200px;
}

.review-textarea {
  width: 100%;
  min-height: 120px;
  border: none;
  background: transparent;
  font-size: 15px;
  color: #333;
  line-height: 1.5;
  resize: none;
  outline: none;
}

.image-upload-section {
  margin-top: 16px;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.image-item {
  position: relative;
  width: 80px;
  height: 80px;
}

.uploaded-img {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  background: #f5f5f5;
}

.delete-btn {
  position: absolute;
  top: -6px;
  right: -6px;
  width: 20px;
  height: 20px;
  background: rgba(0, 0, 0, 0.6);
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  cursor: pointer;
}

.add-image-btn {
  width: 80px;
  height: 80px;
  border: 2px dashed #ddd;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.2s;
  
  &:hover {
    border-color: #ff6b35;
  }
}

.camera-icon {
  font-size: 24px;
  color: #999;
  margin-bottom: 4px;
}

.add-text {
  font-size: 12px;
  color: #999;
}

.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 16px;
  border-top: 1px solid #f0f0f0;
}

.anonymous-option {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.checkbox {
  width: 20px;
  height: 20px;
  border: 2px solid #ddd;
  border-radius: 50%;
  margin-right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  
  &.checked {
    background: #ff6b35;
    border-color: #ff6b35;
  }
  
  .checkmark {
    color: #fff;
    font-size: 12px;
    font-weight: bold;
  }
}

.anonymous-text {
  font-size: 15px;
  color: #333;
}

.submit-btn {
  width: 100%;
  height: 44px;
  background: linear-gradient(90deg, #ff6b35 0%, #ff8c42 100%);
  color: #fff;
  border: none;
  border-radius: 22px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: opacity 0.2s;
  
  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
  
  &:not(:disabled):hover {
    opacity: 0.9;
  }
}
</style> 